package cn.edu.zjicm.wordsnet_d.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.base.LoginWeixinBaseActivity;
import cn.edu.zjicm.wordsnet_d.data.MobclickAgentData;
import cn.edu.zjicm.wordsnet_d.data.StaticData;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.DataValidator;
import cn.edu.zjicm.wordsnet_d.view.EmailAutoCompleteTextView;
import cn.edu.zjicm.wordsnet_d.view.MyDialog;
import cn.edu.zjicm.wordsnet_d.wxapi.WXEntryActivity;

import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

public class RegisterActivity extends LoginWeixinBaseActivity implements OnClickListener, OnFocusChangeListener {

	public static final int TO_PUNCH_OUT = 0; // 点击打卡
	// public static final int TO_SCHOOL_RANK = 1;
	public static final int TO_MAIN = -1; // 到主界面
	public static final int TO_SETTING = 2; // 点击设置界面的同步时，需要登录
	public static final int TO_LEADER_BOARD = 3; // 点击排行榜
	public static final int TO_PAY = 4; // 选择需要用知米豆的单词书
	public static final int TO_PERSON_ACCOUNT = 5; // 点击头像
	public static final int TO_CALENDAR = 6; // 点击打卡日历的补打卡
	public static final int FROM_NEW_USER = 10;

	public static void startActivity(Context context, int nextOperation) {
		Intent i = new Intent(context, RegisterActivity.class);
		i.putExtra("nextOperation", nextOperation);
		context.startActivity(i);
	}

	public static void startActivity(Context context, int fromOperation, int nextOperation) {
		Intent i = new Intent(context, RegisterActivity.class);
		i.putExtra("nextOperation", nextOperation);
		i.putExtra("fromOperation", fromOperation);
		context.startActivity(i);
	}

	// public static void startActivity(Context context, int keyCode, int
	// nextOperation) {
	// Intent i = new Intent(context, RegisterActivity.class);
	// i.putExtra("nextOperation", nextOperation);
	// i.putExtra("keyCode", keyCode);
	// context.startActivity(i);
	// }

	private EditText password;
	private EmailAutoCompleteTextView email;
	private Button register;
	private TextView protocolText;
	private ImageView email_clear;
	private SpannableString ss;
	private InputMethodManager imm;
	private TextView toLoginTv;
	private TextView showPwd;

	private boolean pwdIsHidden = true;

	private RelativeLayout loginWithWechat;
	public static RegisterActivity mContext;

	public static int nextOperation = TO_MAIN;
	public static int fromOperation = 0;

	Handler registerHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START)
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}

			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(RegisterActivity.this, null, "正在注册...");
				break;
			case UserInterface.MSG_SUCCESS:
				toSync();
				MobclickAgentData.register(RegisterActivity.this, "注册成功");
				AppPreference.setFirstGuidePage(RegisterActivity.this, false);
				// 注册接口已经上传过经验值，此处暂不上传经验值
				// AppPreference.setEXPUpdated(RegisterActivity.this, false);
				// ExpInterface.getInstance(RegisterActivity.this).setExp();
				break;
			case UserInterface.MSG_REGISTERED:
				Toast.makeText(RegisterActivity.this, "已被注册，请登录或换邮箱注册", Toast.LENGTH_SHORT).show();
				MobclickAgentData.register(RegisterActivity.this, "注册失败，邮箱已被注册");
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(RegisterActivity.this, UserInterface.MSG_BAD_NETWORK_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.register(RegisterActivity.this, "注册失败，未检测到网络连接");
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(RegisterActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.register(RegisterActivity.this, "注册失败，连接服务器失败");
				break;
			case UserInterface.MSG_WEB_SITE_ERROR:
				Toast.makeText(RegisterActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.register(RegisterActivity.this, "注册失败，服务器错误");
				break;
			default:
				break;
			}
		};
	};

	Handler syncHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START)
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}

			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(RegisterActivity.this, null, "正在同步用户数据...");
				break;
			case UserInterface.MSG_SUCCESS:
				Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
				MobclickAgentData.register(RegisterActivity.this, "注册成功，同步成功");
				if (LoginActivity.mLoginActivity != null) {
					LoginActivity.mLoginActivity.toFinish();
				}

				if (GuideActivityFull.mInstance != null) {
					GuideActivityFull.mInstance.toFinish();
				}

				if (nextOperation == TO_PERSON_ACCOUNT) {
					PersonalAccountActivity.startActivity(mContext, PersonalAccountActivity.TYPE_REGISTER);
				} else if (nextOperation == TO_LEADER_BOARD) {
					LeaderboardActivity.startActivity(mContext);
				} else if (nextOperation == TO_SETTING || nextOperation == TO_MAIN) {
					if (AppPreference.hasStudyingBook(RegisterActivity.this))
						MainActivity.startActivity(RegisterActivity.this);
					else
						SelectBookActivity.mStartActivity(RegisterActivity.this, StaticData.MODE_INIT);
				}

				toFinish();
				break;
			case UserInterface.MSG_UNSUCCESS:
				Toast.makeText(RegisterActivity.this, "同步失败", Toast.LENGTH_SHORT).show();
				MobclickAgentData.register(RegisterActivity.this, "注册失败，同步失败");
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(RegisterActivity.this, UserInterface.MSG_BAD_NETWORK_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.register(RegisterActivity.this, "注册失败，同步失败，未检测到网络连接");
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(RegisterActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.register(RegisterActivity.this, "注册失败，同步失败，连接服务器失败");
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleBarStyle(TITLE_BAR_STYLE_BACK_BUTTON);
		setTitleText("注册知米帐号");
		setContentView(R.layout.activity_register);
		nextOperation = getIntent().getIntExtra("nextOperation", TO_MAIN);
		fromOperation = getIntent().getIntExtra("fromOperation", 0);
		if (nextOperation == TO_PUNCH_OUT || nextOperation == TO_SETTING) {
			overridePendingTransition(R.anim.zoom_in, 0);
		}
		mContext = RegisterActivity.this;

		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		// protocolText = (TextView) findViewById(R.id.protocol);
		// protocolText.setOnClickListener(this);

		toLoginTv = (TextView) findViewById(R.id.to_login);
		toLoginTv.setOnClickListener(this);

		email = (EmailAutoCompleteTextView) findViewById(R.id.register_email);
		email.setText(getIntent().getStringExtra("email"));
		System.out.println("register中得到的Email：" + getIntent().getStringExtra("email"));
		email.setOnFocusChangeListener(this);
		password = (EditText) findViewById(R.id.register_pwd);
		password.setOnFocusChangeListener(this);
		showPwd = (TextView) findViewById(R.id.show_pwd);
		showPwd.setOnClickListener(this);

		register = (Button) findViewById(R.id.register_btn);
		register.setOnClickListener(this);

		email_clear = (ImageView) findViewById(R.id.register_email_clear);

		email_clear.setOnClickListener(this);

		email.addTextChangedListener(textWatcher);
		password.addTextChangedListener(textWatcher);
		password.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEND) {
					if (register.isEnabled()) {
						checkAndRegister();
					}
					return true;
				}
				return false;
			}
		});

		loginWithWechat = (RelativeLayout) findViewById(R.id.login_button_wechat);
		loginWithWechat.setOnClickListener(this);

		setBackButton(new OnClickListener() {

			@Override
			public void onClick(View v) {
				toFinish();
			}
		});
		if (fromOperation == FROM_NEW_USER)
			setRightText("跳过", new OnClickListener() {
				@Override
				public void onClick(View v) {
					AppPreference.setFirstGuidePage(RegisterActivity.this, false);
					if (AppPreference.hasStudyingBook(RegisterActivity.this)) {
						MainActivity.startActivity(RegisterActivity.this);
						toFinish();
					} else {
						SelectBookActivity.mStartActivity(RegisterActivity.this, StaticData.MODE_INIT);
					}

				}
			});
	}

	private MyDialog mRegisterCheckWindow;

	void show_register_check_window() {
		View view = View.inflate(this, R.layout.window_check_register, null);
		if (mRegisterCheckWindow == null) {
			Button confirmButton = (Button) view.findViewById(R.id.set_to_familiar_confirm_button);
			Button cancleButton = (Button) view.findViewById(R.id.set_to_familiar_cancle_button);
			TextView userLoginIDText = (TextView) view.findViewById(R.id.user_login_id);
			userLoginIDText.setText(email.getText());
			confirmButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mRegisterCheckWindow.dismiss();
					mRegisterCheckWindow = null;
					toRegister();
				}
			});
			cancleButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mRegisterCheckWindow.dismiss();
					mRegisterCheckWindow = null;
				}
			});

			mRegisterCheckWindow = new MyDialog(this, view, R.style.mydialog, false);
			mRegisterCheckWindow.setCanceledOnTouchOutside(true);
			mRegisterCheckWindow.setOnDismissListener(new DialogInterface.OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface dialog) {
					mRegisterCheckWindow = null;
				}
			});

		}
		mRegisterCheckWindow.show();
	}

	protected void toRegister() {
		registerHandler.sendMessage(registerHandler.obtainMessage(UserInterface.MSG_START));
		UserInterface.getInstance(RegisterActivity.this).register(email.getText().toString(), password.getText().toString(), registerHandler);
	}

	protected void toSync() {
		syncHandler.sendMessage(syncHandler.obtainMessage(UserInterface.MSG_START));
		UserInterface.getInstance(RegisterActivity.this).sync(syncHandler);
	}

	void checkRegisterInfo() {
		boolean flag = true;
		if (DataValidator.EditIsNull(email.getText().toString())) {
			flag = false;
			email_clear.setVisibility(View.GONE);
		} else {
			email_clear.setVisibility(View.VISIBLE);
		}
		if (DataValidator.EditIsNull(password.getText().toString())) {
			flag = false;
		}

		if (flag) {
			register.setEnabled(true);
		} else {
			register.setEnabled(false);
		}
	}

	TextWatcher textWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			checkRegisterInfo();
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.register_email_clear:
			email.setText("");
			email_clear.setVisibility(View.GONE);
			break;

		case R.id.register_btn:
			checkAndRegister();
			break;
		case R.id.to_login:
			if (LoginActivity.mLoginActivity != null) {
				toFinish();
			} else {
				Intent in = new Intent(mContext, LoginActivity.class);
				startActivity(in);
			}
			break;
		// case R.id.protocol:
		// Intent in = new Intent(mContext, AgreementActivity.class);
		// startActivity(in);
		// break;
		case R.id.login_button_wechat:
			loginWithWeChat();
			break;
		case R.id.show_pwd:

			if (pwdIsHidden) {
				password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
				password.setSelection(password.getText().length());
				showPwd.setText("隐藏");
			} else {
				password.setTransformationMethod(PasswordTransformationMethod.getInstance());
				password.setSelection(password.getText().length());
				showPwd.setText("显示");
			}
			pwdIsHidden = !pwdIsHidden;
			break;
		}
	}

	private void checkAndRegister() {
		if (!DataValidator.EmailIsValidate(email.getText().toString())) {
			Toast.makeText(RegisterActivity.this, "请填入正确的电子邮箱", Toast.LENGTH_SHORT).show();
		} else if (!DataValidator.PwdIsValidate(password.getText().toString())) {
			Toast.makeText(RegisterActivity.this, "密码格式错误，请输入6~16位数字或字母", Toast.LENGTH_SHORT).show();
		} else {
			show_register_check_window();
			imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
		}
		// PersonalAccountActivity.startActivity(mContext,
		// PersonalAccountActivity.TYPE_REGISTER);
	}

	IWXAPI apiWeChat;

	private void loginWithWeChat() {
		apiWeChat = WXAPIFactory.createWXAPI(this, StaticData.APP_ID_WECHAT);
		if (apiWeChat.isWXAppInstalled()) {
			final SendAuth.Req req = new SendAuth.Req();
			req.scope = "snsapi_userinfo";
			req.state = "ZhiMi_English";
			apiWeChat.sendReq(req);
			WXEntryActivity.context = this;
		} else {
			Toast.makeText(RegisterActivity.this, "安装微信客户端后才能登录哦", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		switch (v.getId()) {
		case R.id.register_email:
			if (v.hasFocus() && !DataValidator.EditIsNull(email.getText().toString())) {
				email_clear.setVisibility(View.VISIBLE);
			} else {
				email_clear.setVisibility(View.GONE);
			}
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean consumed = false;
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			toFinish();
		}
		return consumed;
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	public void toFinish() {
		finish();
		mContext = null;
		if (nextOperation == TO_PUNCH_OUT || nextOperation == TO_SETTING) {
			overridePendingTransition(0, R.anim.zoom_out);
		}
	}

}
